/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller.SRV;

import entity.MHotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.MHotelFacade;
import util.jQgrid.JQGridFormatterUtil;
import util.jQgrid.JQGridRow;

/**
 *
 * @author up2u
 */
@WebServlet(name="SRV_MHotelList"
                ,loadOnStartup = 1
                ,urlPatterns={"/SRV/MHotelList"
                                , "/SRV/MHotelList/grd_search"
                                , "/SRV/MHotelList/grd_delete"})
public class SRV_MHotelList extends HttpServlet {
    @EJB
    private MHotelFacade mHotelFacade;
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SRV_MHotelList</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet SRV_MHotelList at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        // if category page is requested
        if (userPath.equals("/SRV/MHotelList")) {
            userPath = "/SRV/MHotelList";
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as
        // 8-bit Unicode (e.g., for Czech characters)
        Boolean isDispatcher = true; //กำหนดว่า ต้องการให้เปลี่ยนหน้าหรือไม่ ? ต้องการ : ไม่ต้องการ
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        if (userPath.equals("/SRV/MHotelList/grd_search")) {
            response.setContentType("text/json;charset=utf-8");
            String qstr_page = request.getParameter("page"); // get the requested page
            String qstr_limit = request.getParameter("rows"); // get how many rows we want to have into the grid
            String qstr_sidx = request.getParameter("sidx"); // get index row - i.e. user click to sort
            String qstr_sord = request.getParameter("sord"); // get the direction

            if (qstr_sidx.isEmpty()) {
                qstr_sidx = "id";
                qstr_sord = "asc";
            }

            String txtName = (request.getParameter("txtName") != null) ? request.getParameter("txtName") : "";
            String txtLocation = (request.getParameter("txtLocation") != null) ? request.getParameter("txtLocation") : "";
            String txtHotelLvl = (request.getParameter("txtHotelLvl") != null) ? request.getParameter("txtHotelLvl") : "";

            PrintWriter out = response.getWriter();
            List<MHotel> lMHotel;
            List rows;
            JQGridRow row;
            List cells;
            String strJson = "";
            int totalRecords = 0;
            int endList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page);
            int startList = Integer.parseInt(qstr_limit)*Integer.parseInt(qstr_page) - Integer.parseInt(qstr_limit);
            try {
                //Query Java Object
                lMHotel = mHotelFacade.LoadDataHotel(txtName, txtLocation, txtHotelLvl, qstr_sidx, qstr_sord);
                totalRecords = lMHotel.size();
                if (endList>totalRecords){
                    endList=totalRecords;
                }
                //Use List rows
                rows = new ArrayList();
                if (!lMHotel.isEmpty()) {
                    for (MHotel obj : lMHotel.subList(startList, endList)) {
                        row = new JQGridRow();
                        row.setId(obj.getId());

                        cells = new ArrayList();
                        cells.add(obj.getId().toString());
                        cells.add(obj.getName());
                        cells.add(obj.getLocation());
                        cells.add(obj.getHotelLevel());
                        if (obj.getLatitude() != null){
                            cells.add(obj.getLatitude().toString());
                        }else{
                            cells.add("");
                        }
                        if (obj.getLongtitude() != null){
                            cells.add(obj.getLongtitude().toString());
                        }else{
                            cells.add("");
                        }
                        row.setCell(cells);
                        rows.add(row);
                    }
                }

                strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(qstr_page), Integer.parseInt(qstr_limit), totalRecords, rows);
                out.println(strJson);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
                lMHotel = null;
                rows = null;
                row = null;
                cells = null;
                strJson = null;
            }

            isDispatcher = false;
        }

        if (userPath.equals("/SRV/MHotelList/grd_delete")) {
            PrintWriter out = response.getWriter();

            String deleteID = (request.getParameter("id") != null) ? request.getParameter("id") : "";
            try {
                mHotelFacade.DeleteHotel(deleteID);
            } catch (Exception ex) {
                System.out.println("Error message" + ex.getMessage());
            } finally {
                out.close();
            }
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            if (isDispatcher) {
                request.getRequestDispatcher(url).forward(request, response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

    }


    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
